using System;
using System.Collections;
using System.Data;
using PCSComMaterials.Plan.DS;
using PCSComProcurement.Purchase.DS;
using PCSComUtils.MasterSetup.DS;
using PCSComUtils.Common;
using PCSComUtils.DataContext;
using System.Transactions;
using PCSComUtils.DataAccess;
using System.Collections.Generic;
using System.Linq;

namespace PCSComProcurement.Purchase.BO
{
    public class PurchaseOrderBO //: IPurchaseOrderBO
    {
        private const string THIS = "PCSComProcurement.Purchase.BO.PurchaseOrderBO";
        public PurchaseOrderBO()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        //**************************************************************************              
        ///    <Description>
        ///       This method uses to get master vo
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Thursday, February 24, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public object GetMasterVO(int pintPOMasterID)
        {
            PO_PurchaseOrderMasterDS dsMaster = new PO_PurchaseOrderMasterDS();
            return dsMaster.GetObjectVO(pintPOMasterID);
        }
        //**************************************************************************              
        ///    <Description>
        ///       This method uses to get full info
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Thursday, February 24, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public DataRow LoadObjectVO(int pintID)
        {
            PO_PurchaseOrderMasterDS dsMaster = new PO_PurchaseOrderMasterDS();
            return dsMaster.LoadObjectVO(pintID);
        }
        
        //**************************************************************************              
        ///    <Description>
        ///       This method uses to 
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Thursday, February 24, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public DataSet ListDetailByMaster(int pintID)
        {
            PO_PurchaseOrderDetailDS dsDetail = new PO_PurchaseOrderDetailDS();
            return dsDetail.List(pintID);
        }

        //**************************************************************************              
        ///    <Description>
        ///       This method uses to 
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Thursday, February 24, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public object GetExchangeRate(int pintCurrencyID, DateTime pdtmOrderDate)
        {
            MST_ExchangeRateDS dsMST = new MST_ExchangeRateDS();
            return dsMST.GetExchangeRate(pintCurrencyID, pdtmOrderDate);
        }
        public MST_ExchangeRate GetExchangeRateDetail(int iCurrencyID, DateTime dtmOrderDate)
        {
            MST_ExchangeRate objReturn = null;
            using (var trans = new TransactionScope())
            {
                using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
                {
                    objReturn = db.MST_ExchangeRates.FirstOrDefault(e => e.CurrencyID == iCurrencyID && e.BeginDate <= dtmOrderDate && e.EndDate >= dtmOrderDate);
                    trans.Complete();
                }
            }
            return objReturn;
        }
        //Update PurchaseOrder
        public bool Update(PO_PurchaseOrderMaster pvoSOMaster, List<PO_PurchaseOrderDetail> listDetail)
        {
            bool ret = true;
            using (var trans = new TransactionScope())
            {
                using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
                {
                    try
                    {
                        //Update Purchase Order Master
                        var objMaster = db.PO_PurchaseOrderMasters.SingleOrDefault(e => e.PurchaseOrderMasterID == pvoSOMaster.PurchaseOrderMasterID);
                        objMaster.BuyerID = pvoSOMaster.BuyerID;
                        objMaster.CarrierID = pvoSOMaster.CarrierID;
                        objMaster.CCNID = pvoSOMaster.CCNID;
                        objMaster.Code = pvoSOMaster.Code;
                        objMaster.Comment = pvoSOMaster.Comment;
                        objMaster.CurrencyID = pvoSOMaster.CurrencyID;
                        objMaster.DeliveryTermsID = pvoSOMaster.DeliveryTermsID;
                        objMaster.DiscountTermID = pvoSOMaster.DiscountTermID;
                        objMaster.ExchangeRate = pvoSOMaster.ExchangeRate;
                        objMaster.ImportTax = pvoSOMaster.ImportTax;
                        objMaster.InvToLocID = pvoSOMaster.InvToLocID;
                        objMaster.LastChange = pvoSOMaster.LastChange;
                        objMaster.MakerID = pvoSOMaster.MakerID;
                        objMaster.MakerLocationID = pvoSOMaster.MakerLocationID;
                        objMaster.MasterLocationID = pvoSOMaster.MasterLocationID;
                        objMaster.OrderDate = pvoSOMaster.OrderDate;
                        objMaster.PartyContactID = pvoSOMaster.PartyContactID;
                        objMaster.PartyID = pvoSOMaster.PartyID;
                        objMaster.PauseID = pvoSOMaster.PauseID;
                        objMaster.PaymentTermsID = pvoSOMaster.PaymentTermsID;
                        objMaster.PORevision = pvoSOMaster.PORevision;
                        objMaster.PricingTypeID = pvoSOMaster.PricingTypeID;
                        objMaster.Priority = pvoSOMaster.Priority;
                        objMaster.PurchaseTypeID = pvoSOMaster.PurchaseTypeID;
                        objMaster.RecCompleted = pvoSOMaster.RecCompleted;
                        objMaster.ReferenceNo = pvoSOMaster.ReferenceNo;
                        objMaster.RequestDeliveryTime = pvoSOMaster.RequestDeliveryTime;
                        objMaster.ShipToLocID = pvoSOMaster.ShipToLocID;
                        objMaster.SpecialTax = pvoSOMaster.SpecialTax;
                        objMaster.TotalAmount = pvoSOMaster.TotalAmount;
                        objMaster.TotalDiscount = pvoSOMaster.TotalDiscount;
                        objMaster.TotalImportTax = pvoSOMaster.TotalImportTax;
                        objMaster.TotalNetAmount = pvoSOMaster.TotalNetAmount;
                        objMaster.TotalSpecialTax = pvoSOMaster.TotalSpecialTax;
                        objMaster.TotalVAT = pvoSOMaster.TotalVAT;
                        objMaster.UserName = pvoSOMaster.UserName;
                        objMaster.VAT = pvoSOMaster.VAT;
                        objMaster.VendorLocID = pvoSOMaster.VendorLocID;
                        objMaster.VendorSO = pvoSOMaster.VendorSO;
                        db.SubmitChanges();
                        foreach (PO_PurchaseOrderDetail objDetail in listDetail)
                        {
                            if (objDetail.PurchaseOrderDetailID > 0)
                            {//Update Purchase Order Detail
                                var obj = db.PO_PurchaseOrderDetails.SingleOrDefault(e => e.PurchaseOrderDetailID == objDetail.PurchaseOrderDetailID);
                                obj.Adjustment1 = objDetail.Adjustment1;
                                obj.Adjustment2 = objDetail.Adjustment2;
                                obj.ApprovalDate = objDetail.ApprovalDate;
                                obj.ApproverID = objDetail.ApproverID;
                                obj.BuyingUMID = objDetail.BuyingUMID;
                                obj.Closed = objDetail.Closed;
                                obj.DiscountAmount = objDetail.DiscountAmount;
                                obj.ImportTax = objDetail.ImportTax;
                                obj.ImportTaxAmount = objDetail.ImportTaxAmount;
                                obj.Line = objDetail.Line;
                                obj.NetAmount = objDetail.NetAmount;
                                obj.OrderQuantity = objDetail.OrderQuantity;
                                obj.ProductID = objDetail.ProductID;
                                obj.PurchaseOrderMasterID = pvoSOMaster.PurchaseOrderMasterID;
                                obj.ReOpen = objDetail.ReOpen;
                                obj.RequiredDate = objDetail.RequiredDate;
                                obj.SpecialTax = objDetail.SpecialTax;
                                obj.SpecialTaxAmount = objDetail.StockUMID;
                                obj.TotalAmount = objDetail.TotalAmount;
                                obj.TotalDelivery = objDetail.TotalDelivery;
                                obj.UMRate = objDetail.UMRate;
                                obj.UnitPrice = objDetail.UnitPrice;
                                obj.VAT = objDetail.VAT;
                                obj.VATAmount = objDetail.VATAmount;
                                obj.VendorItem = objDetail.VendorItem;
                                obj.VendorRevision = objDetail.VendorRevision;
                                db.SubmitChanges();
                                //Update delivery schedule
                                var objDelivery = db.PO_DeliverySchedules.SingleOrDefault(e => e.PurchaseOrderDetailID == obj.PurchaseOrderDetailID);
                                if (objDelivery == null)
                                {
                                    objDelivery = new PO_DeliverySchedule();
                                    objDelivery.PurchaseOrderDetailID = objDetail.PurchaseOrderDetailID;
                                    objDelivery.DeliveryLine = objDetail.Line;
                                    if (objDetail.OrderQuantity != null)
                                        objDelivery.DeliveryQuantity = objDetail.OrderQuantity ?? 0;
                                    if (objDetail.RequiredDate != null)
                                        objDelivery.ScheduleDate = objDetail.RequiredDate ?? DateTime.Today;
                                    db.PO_DeliverySchedules.InsertOnSubmit(objDelivery);
                                }
                                else
                                {
                                    objDelivery.PurchaseOrderDetailID = objDetail.PurchaseOrderDetailID;
                                    objDelivery.DeliveryLine = objDetail.Line;
                                    if (objDetail.OrderQuantity != null)
                                        objDelivery.DeliveryQuantity = objDetail.OrderQuantity ?? 0;
                                    if (objDetail.RequiredDate != null)
                                        objDelivery.ScheduleDate = objDetail.RequiredDate ?? DateTime.Today;
                                }
                                db.SubmitChanges();
                            }
                            else
                            {
                                //Insert Purchase Order Detail
                                objDetail.PurchaseOrderMasterID = pvoSOMaster.PurchaseOrderMasterID;
                                db.PO_PurchaseOrderDetails.InsertOnSubmit(objDetail);
                                db.SubmitChanges();
                                //Insert Delivery Schedule
                                PO_DeliverySchedule objDelivery = new PO_DeliverySchedule();
                                objDelivery.PurchaseOrderDetailID = objDetail.PurchaseOrderDetailID;
                                objDelivery.DeliveryLine = objDetail.Line;
                                if (objDetail.OrderQuantity != null)
                                    objDelivery.DeliveryQuantity = objDetail.OrderQuantity ?? 0;
                                if (objDetail.RequiredDate != null)
                                    objDelivery.ScheduleDate = objDetail.RequiredDate ?? DateTime.Today;
                                db.PO_DeliverySchedules.InsertOnSubmit(objDelivery);
                                db.SubmitChanges();
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        ret = true;
                        Transaction.Current.Rollback(ex);
                        throw ex;
                    }
                    finally { trans.Complete(); }
                    return ret;
                }
            }
        }
        public void UpdatePurchaseOrder(object pvoSOMaster, DataSet pdstSODetail)
        {
            PO_PurchaseOrderMasterDS dsMaster = new PO_PurchaseOrderMasterDS();
            PO_PurchaseOrderMasterVO voMaster = (PO_PurchaseOrderMasterVO)pvoSOMaster;
            dsMaster.Update(voMaster);
            if (pdstSODetail != null)
                foreach (DataRow objRow in pdstSODetail.Tables[0].Rows)
                {
                    if (objRow.RowState == DataRowState.Deleted) continue;
                    objRow[PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD] = voMaster.PurchaseOrderMasterID;
                }
            PO_PurchaseOrderDetailDS dsDetail = new PO_PurchaseOrderDetailDS();
            dsDetail.UpdateDataSet(pdstSODetail);

            // create po delivery automatically
            PO_DeliveryScheduleDS dsSchedule = new PO_DeliveryScheduleDS();
            DataSet dstPODetail = dsDetail.List(voMaster.PurchaseOrderMasterID);
            DataSet dstSchedule = dsSchedule.List(voMaster.PurchaseOrderMasterID);
            foreach (DataRow objRow in dstPODetail.Tables[0].Rows)
            {
                DataRow[] drowExist = dstSchedule.Tables[0].Select(PO_DeliveryScheduleTable.PURCHASEORDERDETAILID_FLD + "=" + objRow[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD]);
                if (drowExist.Length == 0)
                {
                    DataRow newrow = dstSchedule.Tables[0].NewRow();

                    newrow[PO_DeliveryScheduleTable.PURCHASEORDERDETAILID_FLD] = objRow[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD];
                    newrow[PO_DeliveryScheduleTable.DELIVERYLINE_FLD] = objRow[PO_PurchaseOrderDetailTable.LINE_FLD];
                    newrow[PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD] = objRow[PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD];
                    newrow[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD] = objRow[PO_PurchaseOrderDetailTable.REQUIREDDATE_FLD];
                    dstSchedule.Tables[0].Rows.Add(newrow);
                }
            }
            DataTable dtbChanges = dstSchedule.Tables[0].GetChanges(DataRowState.Added);
            if (dtbChanges != null && dtbChanges.Rows.Count > 0)
                dsSchedule.UpdateDataSet(dstSchedule);
        }
        //**************************************************************************              
        ///    <Description>
        ///       This method uses to add new 
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Thursday, February 24, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public int AddNewPurchaseOrder(object pvoPOMaster, DataSet pdstPODetail)
        {
            PO_PurchaseOrderMasterDS dsMaster = new PO_PurchaseOrderMasterDS();
            int intPOMasterID = dsMaster.AddAndReturnID(pvoPOMaster);
            foreach (DataRow objRow in pdstPODetail.Tables[0].Rows)
            {
                if (objRow.RowState == DataRowState.Deleted) continue;
                objRow[PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD] = intPOMasterID;
            }
            PO_PurchaseOrderDetailDS dsDetail = new PO_PurchaseOrderDetailDS();
            dsDetail.UpdateDataSet(pdstPODetail);
            // create po delivery automatically
            PO_DeliveryScheduleDS dsSchedule = new PO_DeliveryScheduleDS();
            DataSet dstPODetail = dsDetail.List(intPOMasterID);
            DataSet dstSchedule = dsSchedule.List(0);
            foreach (DataRow objRow in dstPODetail.Tables[0].Rows)
            {
                DataRow newrow = dstSchedule.Tables[0].NewRow();

                newrow[PO_DeliveryScheduleTable.PURCHASEORDERDETAILID_FLD] = objRow[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD];
                newrow[PO_DeliveryScheduleTable.DELIVERYLINE_FLD] = objRow[PO_PurchaseOrderDetailTable.LINE_FLD];
                newrow[PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD] = objRow[PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD];
                newrow[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD] = objRow[PO_PurchaseOrderDetailTable.REQUIREDDATE_FLD];
                dstSchedule.Tables[0].Rows.Add(newrow);
            }
            DataTable dtbChanges = dstSchedule.Tables[0].GetChanges(DataRowState.Added);
            if (dtbChanges != null && dtbChanges.Rows.Count > 0)
                dsSchedule.UpdateDataSet(dstSchedule);
            return intPOMasterID;
        }
        public bool Insert(PO_PurchaseOrderMaster pvoPOMaster, List<PO_PurchaseOrderDetail> listDetail)
        {
            bool ret = true;
            using (var trans = new TransactionScope())
            {
                using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
                {
                    try
                    {
                        db.PO_PurchaseOrderMasters.InsertOnSubmit(pvoPOMaster);
                        db.SubmitChanges();
                        foreach (PO_PurchaseOrderDetail objDetail in listDetail)
                        {
                            objDetail.PurchaseOrderMasterID = pvoPOMaster.PurchaseOrderMasterID;
                            db.PO_PurchaseOrderDetails.InsertOnSubmit(objDetail);
                            db.SubmitChanges();
                            PO_DeliverySchedule objDelivery = new PO_DeliverySchedule();
                            objDelivery.PurchaseOrderDetailID = objDetail.PurchaseOrderDetailID;
                            objDelivery.DeliveryLine = objDetail.Line;
                            if (objDetail.OrderQuantity != null)
                                objDelivery.DeliveryQuantity = objDetail.OrderQuantity ?? 0;
                            if (objDetail.RequiredDate != null)
                                objDelivery.ScheduleDate = objDetail.RequiredDate ?? DateTime.Today;
                            db.PO_DeliverySchedules.InsertOnSubmit(objDelivery);
                            db.SubmitChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        ret = false;
                        throw ex;
                        Transaction.Current.Rollback(ex);
                    }
                    finally { trans.Complete(); }
                    return ret;
                }
            }
        }
        //**************************************************************************              
        ///    <Description>
        ///       This method uses to list 
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Thursday, February 24, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public DataTable ListUnitOfMeasure()
        {
            MST_UnitOfMeasureDS dsUnitOfMeasure = new MST_UnitOfMeasureDS();
            return dsUnitOfMeasure.List().Tables[0];
        }
        public List<MST_UnitOfMeasure> ListMeasureUnit()
        {
            List<MST_UnitOfMeasure> list = new List<MST_UnitOfMeasure>();
            using (var trans = new TransactionScope())
            {
                using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
                {
                    list = db.GetTable<MST_UnitOfMeasure>().ToList();
                    trans.Complete();
                }
            }
            return list;
        }
        //**************************************************************************              
        ///    <Description>
        ///       This method uses to list 
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Thursday, February 24, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public MST_UnitOfMeasure GetUnitOfMeasureDetail(int iUMID)
        {
            MST_UnitOfMeasure objReturn = new MST_UnitOfMeasure();
            using (var trans = new TransactionScope())
            {
                using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
                {
                    objReturn = db.MST_UnitOfMeasures.Single(e => e.UnitOfMeasureID == iUMID);
                    trans.Complete();
                }
            }
            return objReturn;
        }
        public object GetUnitOfMeasure(int pintID)
        {
            MST_UnitOfMeasureDS dsUnitOfMeasure = new MST_UnitOfMeasureDS();
            return dsUnitOfMeasure.GetObjectVO(pintID);
        }

        //**************************************************************************              
        ///    <Description>
        ///       This method uses to delete
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Friday, March 04, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public void DeletePurchaseOrder(int pintMasterID)
        {
            PO_PurchaseOrderDetailDS dsDetail = new PO_PurchaseOrderDetailDS();
            DataSet dstDetail = dsDetail.List(pintMasterID);
            foreach (DataRow drow in dstDetail.Tables[0].Rows)
            {
                dsDetail.Delete(int.Parse(drow[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD].ToString()));
            }
            PO_PurchaseOrderMasterDS dsMaster = new PO_PurchaseOrderMasterDS();
            dsMaster.Delete(pintMasterID);
        }
        public bool Delete(int iMasterID)
        {
            bool ret = true;
            using (var trans = new TransactionScope())
            {
                using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
                {
                    try
                    {
                        var list = db.PO_PurchaseOrderDetails.Where(e => e.PurchaseOrderMasterID == iMasterID).ToList<PO_PurchaseOrderDetail>();

                        foreach (PO_PurchaseOrderDetail obj in list)
                        {
                            var listtmp = db.PO_DeliverySchedules.Where(e => e.PurchaseOrderDetailID == obj.PurchaseOrderDetailID);
                            db.PO_DeliverySchedules.DeleteAllOnSubmit(listtmp);
                        }
                        db.PO_PurchaseOrderDetails.DeleteAllOnSubmit(list);
                        var objMaster = db.PO_PurchaseOrderMasters.Single(e => e.PurchaseOrderMasterID == iMasterID);
                        db.PO_PurchaseOrderMasters.DeleteOnSubmit(objMaster);
                        db.SubmitChanges();
                    }
                    catch (Exception ex)
                    {
                        ret = false;
                        Transaction.Current.Rollback();
                    }
                    finally
                    {
                        trans.Complete();
                    }
                }
            }
            return ret;
        }        

        /// <summary>
        /// CheckReferenceAndRevisionNo
        /// </summary>
        /// <param name="pstrReferenceNo"></param>
        /// <param name="pstrRevision"></param>
        /// <returns></returns>
        /// <author>Trada</author>
        /// <date>Friday, September 22 2006</date>
        //[AutoComplete(true)]
        public bool CheckReferenceAndRevisionNo(string pstrReferenceNo, string pstrRevision, int pintPOMasterID)
        {
            PO_PurchaseOrderMasterDS dsPurchaseOrderMaster = new PO_PurchaseOrderMasterDS();
            DataSet dstCount = new DataSet();
            dstCount = dsPurchaseOrderMaster.CheckReferenceAndRevisionNo(pstrReferenceNo, pstrRevision, pintPOMasterID);
            if (dstCount.Tables[0].Rows.Count > 0)
            {
                if (int.Parse(dstCount.Tables[0].Rows[0][0].ToString()) > 0)
                {
                    return false;
                }
            }


            return true;
        }
        //**************************************************************************              
        ///    <Description>
        ///       This method uses to 
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Thursday, February 24, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public object GetPurchaseOrderByCode(string pstrCode)
        {
            PO_PurchaseOrderMasterDS dsMaster = new PO_PurchaseOrderMasterDS();
            return dsMaster.GetObjectVO(pstrCode);
        }

        //**************************************************************************              
        ///    <Description>
        ///       This method uses to 
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Thursday, February 24, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public int IsValidateData(string pstrValue, string pstrTable, string pstrField, string pstrCodition)
        {
            PO_PurchaseOrderMasterDS dsMaster = new PO_PurchaseOrderMasterDS();
            return dsMaster.IsValidateData(pstrValue, pstrTable, pstrField, pstrCodition);
        }

        //**************************************************************************              
        ///    <Description>
        ///       This method uses to 
        ///    </Description>
        ///    <Inputs>
        ///            
        ///    </Inputs>
        ///    <Outputs>
        ///       
        ///    </Outputs>
        ///    <Returns>
        ///       
        ///    </Returns>
        ///    <Authors>
        ///       Hoang Trung Son - iSphere software
        ///    </Authors>
        ///    <History>
        ///       Friday, March 25, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public DataRow GetDataRow(string pstrKeyField, string pstrValue, string pstrTable, string pstrField, string pstrCodition)
        {
            PO_PurchaseOrderMasterDS dsMaster = new PO_PurchaseOrderMasterDS();
            return dsMaster.GetDataRow(pstrKeyField, pstrValue, pstrTable, pstrField, pstrCodition);
        }
        public void Add(object pObjectDetail)
        {
            // TODO:  

        }

        public void Delete(object pObjectVO)
        {
            // TODO:  

        }

        public object GetObjectVO(int pintID, string VOclass)
        {
            // TODO:  
            return null;
        }

        public void Update(object pObjectDetail)
        {
            // TODO:  

        }

        public void UpdateDataSet(DataSet dstData)
        {
            // TODO:  

        }

        public DataRow GetVendorLocationByVendor(int pintPartyID)
        {
            return null;
        }
        public DataSet GetItemVendorReference(int pintPartyID, Hashtable pobjProductID)
        {
            return null;
        }

        /// <summary>
        /// Add new for case : Convert CPO to new PO
        /// </summary>
        /// <param name="pdstCPODetail"></param>
        /// <param name="pobjMasterVO"></param>
        /// <param name="pdstDetail"></param>
        ///<author>TuanDM</author>
        //[AutoComplete(true)]
        public int AddPOAndDelSchedule(System.Data.DataSet pdstCPODetail, object pobjMasterVO, System.Data.DataSet pdstDetail)
        {
            //Add Master and Get returning ID
            PO_PurchaseOrderMasterDS dsPOMaster = new PO_PurchaseOrderMasterDS();
            int intMasterID = dsPOMaster.AddAndReturnID(pobjMasterVO);

            //Add detail
            ArrayList arlDueDate = new ArrayList();
            foreach (DataRow drowDetail in pdstDetail.Tables[0].Rows)
            {
                drowDetail[PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD] = intMasterID;
                arlDueDate.Add(drowDetail[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD].ToString());
            }
            PO_PurchaseOrderDetailDS dsPODetail = new PO_PurchaseOrderDetailDS();

            dsPODetail.UpdateDataSet(pdstDetail);

            //Get PODetail DataSet which includes PURCHASEORDERDETAILID_FLD
            pdstDetail = dsPODetail.List(intMasterID);

            //Create DeliverySchedule -- and add DeliverySchedule
            PO_DeliveryScheduleVO voSchedule;
            for (int i = 0; i < pdstDetail.Tables[0].Rows.Count; i++)
            {
                voSchedule = new PO_DeliveryScheduleVO();
                voSchedule.DeliveryLine = 1;
                voSchedule.PurchaseOrderDetailID = int.Parse(pdstDetail.Tables[0].Rows[i][PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD].ToString());
                voSchedule.ScheduleDate = DateTime.Parse(arlDueDate[i].ToString());
                voSchedule.DeliveryQuantity = decimal.Parse(pdstDetail.Tables[0].Rows[i][PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD].ToString());
                new PO_DeliveryScheduleDS().Add(voSchedule);
            }

            //Update CPODetail
            new MTR_CPODS().SetPOMasterID(null, intMasterID);

            //return ID
            return intMasterID;
        }
        /// <summary>
        /// Update PO and Delivery Schedule in case : CPO to Exist PO
        /// </summary>
        /// <param name="pdstCPODetail"></param>
        /// <param name="pobjMasterVO"></param>
        /// <param name="pdstDetail"></param>
        /// <author>TuanDM</author>
        //[AutoComplete(true)]
        public void UpdatePOAndDelSchedule(System.Data.DataSet pdstCPODetail, object pobjMasterVO, System.Data.DataSet pdstDetail)
        {
            //Update PO Master
            PO_PurchaseOrderMasterDS dsMaster = new PO_PurchaseOrderMasterDS();
            dsMaster.Update(pobjMasterVO);

            //Update PO Detail
            ArrayList arlIndexs = new ArrayList();
            ArrayList arlDueDate = new ArrayList();
            int intinD = -1;
            if (pdstDetail != null)
                foreach (DataRow objRow in pdstDetail.Tables[0].Rows)
                {
                    intinD++;
                    if (objRow.RowState == DataRowState.Deleted) continue;
                    objRow[PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD] = ((PO_PurchaseOrderMasterVO)pobjMasterVO).PurchaseOrderMasterID;
                    if (objRow[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD].ToString() != string.Empty)
                    {
                        arlDueDate.Add(objRow[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD]);
                        arlIndexs.Add(intinD);
                    }
                }
            PO_PurchaseOrderDetailDS dsDetail = new PO_PurchaseOrderDetailDS();
            dsDetail.UpdateDataSet(pdstDetail);

            //Update DeliverySchedule
            pdstDetail = dsDetail.List(((PO_PurchaseOrderMasterVO)pobjMasterVO).PurchaseOrderMasterID);

            //Create DeliverySchedule -- and add DeliverySchedule
            for (int i = 0; i < arlIndexs.Count; i++)
            {
                PO_DeliveryScheduleVO voSchedule = new PO_DeliveryScheduleVO();
                voSchedule.DeliveryLine = 1;
                voSchedule.PurchaseOrderDetailID = int.Parse(pdstDetail.Tables[0].Rows[int.Parse(arlIndexs[i].ToString())][PO_DeliveryScheduleTable.PURCHASEORDERDETAILID_FLD].ToString());
                voSchedule.ScheduleDate = DateTime.Parse(arlDueDate[i].ToString());
                voSchedule.DeliveryQuantity = decimal.Parse(pdstDetail.Tables[0].Rows[int.Parse(arlIndexs[i].ToString())][PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD].ToString());
                new PO_DeliveryScheduleDS().Add(voSchedule);
            }

            //Update CPODetail
            new MTR_CPODS().SetPOMasterID(null, ((PO_PurchaseOrderMasterVO)pobjMasterVO).PurchaseOrderMasterID);
        }
        public DataRow GetVendorContact(int pintPartyLocationID)
        {
            return null;
        }


        /// <summary>
        /// Add new for case : Convert CPO to new PO
        /// </summary>
        /// <param name="pobjMasterVO"></param>
        /// <param name="pdstDetail"></param>
        /// <param name="pdstDelivery"></param>
        ///<author>TuanDM</author>
        //[AutoComplete(true)]
        public int AddPOAndDelScheduleImmediate(object pobjMasterVO, System.Data.DataSet pdstDetail, DataSet pdstDelivery, ArrayList parlCPOIDs)
        {
            //Add Master and Get returning ID
            PO_PurchaseOrderMasterDS dsPOMaster = new PO_PurchaseOrderMasterDS();
            int intMasterID = dsPOMaster.AddAndReturnID(pobjMasterVO);

            //Add detail
            foreach (DataRow drowDetail in pdstDetail.Tables[0].Rows)
            {
                drowDetail[PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD] = intMasterID;
            }
            PO_PurchaseOrderDetailDS dsPODetail = new PO_PurchaseOrderDetailDS();
            dsPODetail.UpdateDataSet(pdstDetail);

            //Get PODetail DataSet which includes PURCHASEORDERDETAILID_FLD
            pdstDetail = dsPODetail.ListToGetID(intMasterID);

            //Create DeliverySchedule -- and add DeliverySchedule
            int intPOLineID = 0;
            int i = 0;
            PO_DeliveryScheduleDS dsDelivery = new PO_DeliveryScheduleDS();

            while (i++ < pdstDetail.Tables[0].Rows.Count)
            {
                DataSet dstNewDelPO = pdstDelivery.Clone();

                DataRow[] drowSameDelivery = pdstDelivery.Tables[0].Select(ITM_ProductTable.PRODUCTID_FLD + "='" + pdstDetail.Tables[0].Rows[i - 1][ITM_ProductTable.PRODUCTID_FLD].ToString() + "'");

                intPOLineID = (int)pdstDetail.Tables[0].Rows[i - 1][PO_DeliveryScheduleTable.PURCHASEORDERDETAILID_FLD];
                for (int j = 0; j < drowSameDelivery.Length; j++)
                {
                    int k = GetIndexForDeliveryLine(dstNewDelPO, (DateTime)drowSameDelivery[j][PO_DeliveryScheduleTable.SCHEDULEDATE_FLD]);
                    if (k > -1)
                    {
                        dstNewDelPO.Tables[0].Rows[k][PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD] = (decimal)dstNewDelPO.Tables[0].Rows[k][PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD] + (decimal)drowSameDelivery[j][PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD];
                        drowSameDelivery[j][PO_DeliveryScheduleTable.PURCHASEORDERDETAILID_FLD] = intPOLineID;
                    }
                    else
                    {
                        drowSameDelivery[j][PO_DeliveryScheduleTable.PURCHASEORDERDETAILID_FLD] = intPOLineID;
                        drowSameDelivery[j][PO_DeliveryScheduleTable.DELIVERYLINE_FLD] = dstNewDelPO.Tables[0].Rows.Count + 1;
                        dstNewDelPO.Tables[0].ImportRow(drowSameDelivery[j]);
                    }
                }
                dsDelivery.UpdateDataSet(dstNewDelPO);
            }
            //Update CPODetail
            MTR_CPODS dsCPO = new MTR_CPODS();
            if (parlCPOIDs.Count > 0)
            {
                if (Convert.ToInt32(parlCPOIDs[0]) > 0)
                {
                    dsCPO.SetPOMasterID(parlCPOIDs, intMasterID);
                }
                else
                {
                    dsCPO.SetPOMasterIDForDCPDetail(parlCPOIDs, intMasterID);
                }
            }

            return intMasterID;
        }

        /// <summary>
        /// Add new for case : Convert CPO to new PO
        /// </summary>
        /// <param name="pobjMasterVO"></param>
        /// <param name="pdstDetail"></param>
        /// <param name="pdstDelivery"></param>
        ///<author>TuanDM</author>
        //[AutoComplete(true)]
        public void UpdatePOAndDelScheduleImmediate(object pobjMasterVO, System.Data.DataSet pdstDetail, DataSet pdstDelivery, ArrayList parlCPOIDs)
        {
            //Add Master and Get returning ID
            PO_PurchaseOrderMasterDS dsPOMaster = new PO_PurchaseOrderMasterDS();
            dsPOMaster.Update(pobjMasterVO);

            //Update detail
            DataSet dstPODetail = pdstDetail.Copy();
            PO_PurchaseOrderDetailDS dsPODetail = new PO_PurchaseOrderDetailDS();
            foreach (DataRow drowDetail in pdstDetail.Tables[0].Rows)
            {
                if (drowDetail.RowState == DataRowState.Added)
                {
                    drowDetail[PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD] = ((PO_PurchaseOrderMasterVO)pobjMasterVO).PurchaseOrderMasterID;
                }
            }
            dsPODetail.UpdateDataSet(pdstDetail);

            //Get PODetail DataSet which includes PURCHASEORDERDETAILID_FLD
            pdstDetail = dsPODetail.ListToGetID(((PO_PurchaseOrderMasterVO)pobjMasterVO).PurchaseOrderMasterID);

            //Create DeliverySchedule -- and add DeliverySchedule
            int intPOLineID = 0;
            PO_DeliveryScheduleDS dsDelivery = new PO_DeliveryScheduleDS();
            for (int i = 0; i < dstPODetail.Tables[0].Rows.Count; i++)
            {
                DataRow[] drowSameDelivery = pdstDelivery.Tables[0].Select(ITM_ProductTable.PRODUCTID_FLD + "='" + dstPODetail.Tables[0].Rows[i][ITM_ProductTable.PRODUCTID_FLD].ToString() + "'");

                intPOLineID = (int)pdstDetail.Tables[0].Select(PO_PurchaseOrderDetailTable.LINE_FLD + "='" + dstPODetail.Tables[0].Rows[i][PO_PurchaseOrderDetailTable.LINE_FLD].ToString() + "'")[0][PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD];
                DataSet dstNewDelPO = dsDelivery.GetDeliverySchedule(intPOLineID);
                int intbaseCount = dstNewDelPO.Tables[0].Rows.Count;
                for (int j = 0; j < drowSameDelivery.Length; j++)
                {
                    int k = GetIndexForDeliveryLine(dstNewDelPO, (DateTime)drowSameDelivery[j][PO_DeliveryScheduleTable.SCHEDULEDATE_FLD]);
                    if (k > -1)
                    {
                        dstNewDelPO.Tables[0].Rows[k][PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD] = (decimal)dstNewDelPO.Tables[0].Rows[k][PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD] + (decimal)drowSameDelivery[j][PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD];
                    }
                    else
                    {
                        drowSameDelivery[j][PO_DeliveryScheduleTable.PURCHASEORDERDETAILID_FLD] = intPOLineID;
                        drowSameDelivery[j][PO_DeliveryScheduleTable.DELIVERYLINE_FLD] = j + 1 + intbaseCount;
                        dstNewDelPO.Tables[0].ImportRow(drowSameDelivery[j]);
                    }
                }
                dsDelivery.UpdateDataSet(dstNewDelPO);
            }

            //Update CPODetail
            MTR_CPODS dsCPO = new MTR_CPODS();
            dsCPO.SetPOMasterID(parlCPOIDs, ((PO_PurchaseOrderMasterVO)pobjMasterVO).PurchaseOrderMasterID);
        }

        private int GetIndexForDeliveryLine(DataSet pdstData, DateTime dtmDuedate)
        {
            int i = 0;
            foreach (DataRow drowData in pdstData.Tables[0].Rows)
            {
                if ((DateTime)drowData[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD] == dtmDuedate)
                    break;
                i += 1;
            }
            if (i == pdstData.Tables[0].Rows.Count) i = -1;
            return i;
        }
        //[AutoComplete(true)]
        public DataTable GetPODomesticData(int pintMasterID)
        {
            PO_PurchaseOrderMasterDS dsMaster = new PO_PurchaseOrderMasterDS();
            return dsMaster.GetPODomesticData(pintMasterID);
        }
    }
}
